package cn.zhiquxing;

import cn.zhiquxing.config.RedisMessageListener;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@SpringBootApplication
@MapperScan({"cn.zhiquxing.mapper", "cn.zhiquxing.dao"})
@EnableConfigurationProperties
@EnableAspectJAutoProxy(exposeProxy = true)
//加载指定配置文件，
@PropertySource(value = {"classpath:test.yml"})
@EnableCaching
@EnableMongoRepositories(basePackages = "cn.zhiquxing.dao")
public class SecurityApplication {
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    
    @Autowired
    private MessageListener redisMessageListener;
    
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    
    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext context = SpringApplication.run(SecurityApplication.class, args);
        System.out.println(context);
        //Thread.currentThread().join();
        
    }
    
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        if (threadPoolTaskScheduler != null) {
            return threadPoolTaskScheduler;
        }
        threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(20);
        return threadPoolTaskScheduler;
    }

    /**
     * 自定义Redis监听容器
     * @return
     */
    @Bean
    public RedisMessageListenerContainer initRedisContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.setTaskExecutor(threadPoolTaskScheduler);
        ChannelTopic topic1 = new ChannelTopic("topic1");
        container.addMessageListener(redisMessageListener, topic1);
        return container;
    }
}